<template>
	<view class="chat-container">
		<!-- 聊天消息列表 -->
		<scroll-view class="message-list" scroll-y :scroll-into-view="scrollToBottom" @scroll="onScroll">
			<!-- 时间分隔线 -->
			<view v-for="(day, index) in groupedMessages" :key="index" class="time-divider">
				<text>{{ formatDay(day.date) }}</text>
			</view>

			<!-- 消息列表 -->
			<view v-for="(item, index) in messages" :key="index" :id="`message-${index}`" class="message-item"
				:class="{ 'is-mine': item.isMine }">
				<!-- 头像 -->
				<image :src="item.isMine ? myAvatar : item.avatar" class="avatar" mode="aspectFill" />

				<!-- 消息内容 -->
				<view class="message-content">
					<!-- 文本消息 -->
					<view v-if="item.type === 'text'" class="text-message">
						{{ item.content }}
					</view>

					<!-- 图片消息 -->
					<image v-else-if="item.type === 'image'" :src="item.content" class="image-message" mode="aspectFill"
						@tap="previewImage(item.content)" />

					<!-- 语音消息 -->
					<view v-else-if="item.type === 'voice'" class="voice-message">
						<view class="voice-icon">
							<text class="iconfont icon-voice"></text>
						</view>
						<text class="voice-duration">{{ item.duration }}''</text>
					</view>
				</view>

				<!-- 消息时间 -->
				<text class="message-time">{{ formatTime(item.time) }}</text>
			</view>

			<!-- 未读消息提示 -->
			<view v-if="hasUnread" class="unread-tip">
				<text>{{ unreadCount }}条未读消息</text>
			</view>
		</scroll-view>

		<!-- 输入区域 -->
		<view class="input-container">
			<!-- 表情按钮 -->
			<view class="action-btn" @tap="toggleEmoji">
				<text class="iconfont icon-emoji"></text>
			</view>

			<!-- 输入框 -->
			<view class="input-wrapper">
				<input v-model="inputMessage" class="message-input" placeholder="输入消息..." @focus="onInputFocus"
					@blur="onInputBlur" @confirm="sendMessage" confirm-type="send" />
			</view>

			<!-- 语音按钮 -->
			<view class="action-btn" @tap="toggleVoiceInput">
				<text class="iconfont" :class="voiceInput ? 'icon-keyboard' : 'icon-voice'"></text>
			</view>

			<!-- 图片按钮 -->
			<view class="action-btn" @tap="chooseImage">
				<text class="iconfont icon-image"></text>
			</view>

			<!-- 发送按钮 -->
			<button v-if="inputMessage && inputMessage.trim()" class="send-btn" @tap="sendMessage" :disabled="!canSend">
				发送
			</button>
		</view>

		<!-- 表情面板 -->
		<view v-if="showEmoji" class="emoji-panel">
			<scroll-view scroll-y class="emoji-list">
				<view v-for="emoji in emojis" :key="emoji" class="emoji-item" @tap="addEmoji(emoji)">
					{{ emoji }}
				</view>
			</scroll-view>
		</view>

		<!-- 语音输入提示 -->
		<view v-if="voiceRecording" class="voice-recording">
			<view class="recording-icon">
				<icon></icon>
				<text class="iconfont icon-voice-big">语音数</text>
			</view>
			<text class="recording-text">松开发送，上滑取消</text>
		</view>
	</view>
</template>

<script setup>
	import { onPullDownRefresh , onReachBottom } from "@dcloudio/uni-app"
	import {
		ref,
		reactive,
		computed,
		onMounted,
		onUnmounted,
		nextTick
	} from 'vue'
	import {
		useRoute,
		useRouter
	} from 'vue-router'
	// uni-app特殊生命周期函数不需要导入，直接使用

	// 路由
	const route = useRoute()
	const router = useRouter()

	// 响应式数据
	const messages = ref([{
			id: 1,
			content: '你好，最近在忙什么呢？',
			type: 'text',
			isMine: false,
			avatar: '/static/avatar/1.jpg',
			time: new Date().getTime() - 3600000,
			duration: 0
		},
		{
			id: 2,
			content: '我最近在学习新技能，感觉很充实！',
			type: 'text',
			isMine: true,
			avatar: '/static/avatar/2.jpg',
			time: new Date().getTime() - 3000000,
			duration: 0
		},
		{
			id: 3,
			content: '/static/common/user/01.png',
			type: 'image',
			isMine: false,
			avatar: '/static/avatar/1.jpg',
			time: new Date().getTime() - 2400000,
			duration: 0
		},
		{
			id: 4,
			content: '',
			type: 'voice',
			isMine: true,
			avatar: '/static/avatar/2.jpg',
			time: new Date().getTime() - 1800000,
			duration: 8
		},
		{
			id: 5,
			content: '周末有空一起参加户外活动吗？',
			type: 'text',
			isMine: false,
			avatar: '/static/avatar/1.jpg',
			time: new Date().getTime() - 1200000,
			duration: 0
		},
		{
			id: 6,
			content: '好啊，有什么推荐的活动吗？',
			type: 'text',
			isMine: true,
			avatar: '/static/avatar/2.jpg',
			time: new Date().getTime() - 600000,
			duration: 0
		}
	])

	const inputMessage = ref('')
	const showEmoji = ref(false)
	const voiceInput = ref(false)
	const voiceRecording = ref(false)
	const scrollToBottom = ref('')
	const hasUnread = ref(false)
	const unreadCount = ref(0)
	const myAvatar = ref('/static/avatar/2.jpg')
	const isScrolledUp = ref(false)

	// 计算属性
	const canSend = computed(() => inputMessage.value ? inputMessage.value.trim().length > 0 : '')
	const groupedMessages = computed(() => {
		// 按日期分组消息
		const groups = {}
		messages.value.forEach(msg => {
			const date = new Date(msg.time).toLocaleDateString()
			if (!groups[date]) {
				groups[date] = {
					date,
					messages: []
				}
			}
			groups[date].messages.push(msg)
		})
		return Object.values(groups)
	})

	// 常用emoji
	const emojis = [
		'😊', '😂', '😍', '🤔', '😎', '😭', '👍', '👎', '❤️', '🎉', '🎁', '✨', '🔥', '🤣', '😘', '🙏',
		]

	// 方法
	const formatTime = (timestamp) => {
		const date = new Date(timestamp)
		const now = new Date()
		const diff = now.getTime() - date.getTime()

		// 小于1分钟
		if (diff < 60000) return '刚刚'

		// 小于1小时
		if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'

		// 今天
		if (date.toDateString() === now.toDateString()) {
			return date.getHours().toString().padStart(2, '0') + ':' + date.getMinutes().toString().padStart(2, '0')
		}

		// 昨天
		const yesterday = new Date(now.getTime() - 86400000)
		if (date.toDateString() === yesterday.toDateString()) return '昨天'

		// 本周
		const weekAgo = new Date(now.getTime() - 604800000)
		if (date > weekAgo) {
			const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
			return weekdays[date.getDay()]
		}

		// 其他
		return date.getMonth() + 1 + '-' + date.getDate()
	}

	const formatDay = (dateStr) => {
		const date = new Date(dateStr)
		const now = new Date()

		// 今天
		if (date.toDateString() === now.toDateString()) return '今天'

		// 昨天
		const yesterday = new Date(now.getTime() - 86400000)
		if (date.toDateString() === yesterday.toDateString()) return '昨天'

		// 本周
		const weekAgo = new Date(now.getTime() - 604800000)
		if (date > weekAgo) {
			const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
			return weekdays[date.getDay()]
		}

		// 其他
		return date.getMonth() + 1 + '月' + date.getDate() + '日'
	}

	const sendMessage = () => {
		if (!canSend.value) return

		// 添加新消息
		messages.value.push({
			id: Date.now(),
			content: inputMessage.value ? inputMessage.value.trim() :'',
			type: 'text',
			isMine: true,
			avatar: myAvatar.value,
			time: Date.now(),
			duration: 0
		})

		// 清空输入框
		inputMessage.value = ''

		// 滚动到底部
		scrollToBottomMessage()

		// 模拟回复（实际项目中应通过API获取）
		setTimeout(() => {
			messages.value.push({
				id: Date.now() + 1,
				content: getRandomReply(),
				type: 'text',
				isMine: false,
				avatar: '/static/avatar/1.jpg',
				time: Date.now(),
				duration: 0
			})
			scrollToBottomMessage()
		}, 1000)
	}

	const getRandomReply = () => {
		const replies = [
			'好的，我知道了',
			'收到，没问题',
			'哈哈哈，有意思',
			'真的吗？太厉害了！',
			'我也这么觉得',
			'那我们约个时间吧',
			'这个想法不错',
			'期待与你见面'
		]
		return replies[Math.floor(Math.random() * replies.length)]
	}

	const scrollToBottomMessage = () => {
		nextTick(() => {
			const lastIndex = messages.value.length - 1
			scrollToBottom.value = `message-${lastIndex}`
			isScrolledUp.value = false
		})
	}

	const onScroll = (e) => {
		const {
			scrollTop,
			scrollHeight,
			clientHeight
		} = e.detail
		// 判断是否滚动到了顶部附近
		isScrolledUp.value = scrollTop < 200
	}

	const toggleEmoji = () => {
		showEmoji.value = !showEmoji.value
		if (showEmoji.value) {
			voiceInput.value = false
		}
	}

	const toggleVoiceInput = () => {
		voiceInput.value = !voiceInput.value
		if (voiceInput.value) {
			showEmoji.value = false
		}
	}

	const addEmoji = (emoji) => {
		inputMessage.value += emoji
	}

	const chooseImage = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				const tempFilePath = res.tempFilePaths[0]
				// 添加图片消息
				messages.value.push({
					id: Date.now(),
					content: tempFilePath,
					type: 'image',
					isMine: true,
					avatar: myAvatar.value,
					time: Date.now(),
					duration: 0
				})
				scrollToBottomMessage()
			}
		})
	}

	const previewImage = (url) => {
		uni.previewImage({
			urls: [url],
			current: url
		})
	}

	const onInputFocus = () => {
		showEmoji.value = false
	}

	const onInputBlur = () => {
		// 输入框失焦逻辑
	}

	// 模拟语音输入开始
	const startVoiceRecording = () => {
		voiceRecording.value = true
		// 实际项目中应调用录音API
	}

	const stopVoiceRecording = (cancel = false) => {
		voiceRecording.value = false
		if (!cancel) {
			// 添加语音消息（模拟）
			const duration = Math.floor(Math.random() * 10) + 3
			messages.value.push({
				id: Date.now(),
				content: '',
				type: 'voice',
				isMine: true,
				avatar: myAvatar.value,
				time: Date.now(),
				duration
			})
			scrollToBottomMessage()
		}
	}

	// 生命周期
	onMounted(() => {
		
		// 进入页面时滚动到底部
		scrollToBottomMessage()
		
		// 设置导航栏标题
		const title = route.params.title || '聊天'
		uni.setNavigationBarTitle({
			title
		})
		
		// 标记为已读
		if (hasUnread.value) {
			hasUnread.value = false
			unreadCount.value = 0
		}
		
		// 组件挂载后的逻辑
		console.log('聊天页面已加载')
	})
	
	
	onPullDownRefresh(() => {
		console.log("下拉刷新")
		setTimeout(function () {
			uni.stopPullDownRefresh();
		}, 1000);
	})
	onReachBottom(() => {
		console.log("上拉加载更多")
	})
		
</script>

<style lang="scss">
	.chat-container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
		padding-bottom: 120rpx;
	}

	// 消息列表样式
	.message-list {
		flex: 1;
		padding: 20rpx;
		-webkit-overflow-scrolling: touch;
	}

	.time-divider {
		display: flex;
		justify-content: center;
		margin: 30rpx 0;

		text {
			font-size: 24rpx;
			color: #999;
			background-color: rgba(0, 0, 0, 0.05);
			padding: 8rpx 20rpx;
			border-radius: 16rpx;
		}
	}

	.message-item {
		display: flex;
		margin-bottom: 30rpx;
		align-items: flex-end;

		&.is-mine {
			flex-direction: row-reverse;
		}
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 40rpx;
		margin: 0 20rpx;
	}

	.message-content {
		max-width: 500rpx;
		word-break: break-word;
	}

	.text-message {
		background-color: #ffffff;
		padding: 20rpx 30rpx;
		border-radius: 20rpx;
		font-size: 28rpx;
		line-height: 1.5;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

		.message-item.is-mine & {
			background-color: #7C3AED;
			color: #ffffff;
		}
	}

	.image-message {
		width: 300rpx;
		height: 300rpx;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.voice-message {
		display: flex;
		align-items: center;
		min-width: 150rpx;
		padding: 20rpx 30rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

		.message-item.is-mine & {
			background-color: #7C3AED;

			.voice-icon text {
				color: #ffffff;
			}

			.voice-duration {
				color: #ffffff;
			}
		}

		.voice-icon {
			margin-right: 10rpx;

			text {
				font-size: 32rpx;
				color: #7C3AED;
			}
		}

		.voice-duration {
			font-size: 24rpx;
			color: #666;
		}
	}

	.message-time {
		font-size: 20rpx;
		color: #999;
		margin: 0 10rpx;
	}

	.unread-tip {
		display: flex;
		justify-content: center;
		margin: 20rpx 0;

		text {
			font-size: 24rpx;
			color: #7C3AED;
			background-color: rgba(124, 58, 237, 0.1);
			padding: 8rpx 20rpx;
			border-radius: 16rpx;
		}
	}

	// 输入区域样式
	.input-container {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		align-items: center;
		padding: 20rpx;
		background-color: #ffffff;
		border-top: 1rpx solid #e5e5e5;
		z-index: 100;
	}

	.action-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		text {
			font-size: 40rpx;
			color: #666;
		}
	}

	.input-wrapper {
		flex: 1;
		background-color: #f5f5f5;
		border-radius: 30rpx;
		margin: 0 10rpx;
		overflow: hidden;
	}

	.message-input {
		width: 100%;
		padding: 20rpx 30rpx;
		font-size: 28rpx;
		background-color: transparent;
		border: none;
		outline: none;
		box-sizing: border-box;
		height: 88rpx;
	}

	.send-btn {
		background-color: #7C3AED;
		color: #ffffff;
		border-radius: 20rpx;
		padding: 0 30rpx;
		height: 60rpx;
		line-height: 60rpx;
		font-size: 28rpx;
		margin-left: 10rpx;

		&:disabled {
			background-color: #ccc;
		}
	}

	// 表情面板样式
	.emoji-panel {
		position: fixed;
		bottom: 100rpx;
		left: 0;
		right: 0;
		height: 300rpx;
		background-color: #ffffff;
		border-top: 1rpx solid #e5e5e5;
		z-index: 99;
	}

	.emoji-list {
		height: 100%;
		padding: 20rpx;

		display: grid;
		grid-template-columns: repeat(8, 1fr);
		gap: 20rpx;
	}

	.emoji-item {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 80rpx;
		font-size: 40rpx;

		&:active {
			background-color: #f5f5f5;
			border-radius: 10rpx;
		}
	}

	// 语音录制提示样式
	.voice-recording {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background-color: rgba(0, 0, 0, 0.8);
		color: #ffffff;
		padding: 40rpx;
		border-radius: 20rpx;
		text-align: center;
		z-index: 999;
	}

	.recording-icon {
		margin-bottom: 20rpx;

		text {
			font-size: 80rpx;
		}
	}

	.recording-text {
		font-size: 28rpx;
	}

	// 图标字体占位（实际项目中应引入图标库）
	.iconfont {
		font-family: 'iconfont';
	}

	// 响应式适配
	@media screen and (min-width: 768px) {
		.chat-container {
			max-width: 750rpx;
			margin: 0 auto;
			border-left: 1rpx solid #e5e5e5;
			border-right: 1rpx solid #e5e5e5;
		}

		.input-container {
			max-width: 750rpx;
			margin: 0 auto;
			border-left: 1rpx solid #e5e5e5;
			border-right: 1rpx solid #e5e5e5;
		}
	}
</style>